package com.store.app.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.R;
import com.store.app.adapter.OrderSellAdapter;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.bean.OrderAdapterBean;
import com.store.app.bean.OrderSellBean;
import com.store.app.bean.OrderSellGoodsBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.AutoListView;
import com.store.app.widget.AutoListView.OnLoadListener;
import com.store.app.widget.AutoListView.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 我的订单
 */
public class TheOrderSellFragment extends Fragment implements IOnHttpListener,OrderSellAdapter.RefreshUI {
    private View v;
    private AutoListView lv;
    private List<OrderSellBean> list;
    private OrderSellAdapter mAdapter;
    //无网络页面
//	private LinearLayout lin_loadfail;
    private ImageView img_fail_nonet;
    private ImageView img_fail_notext;
    private TextView tv_fail;
    private static final int MSG_LOAD_SUCCESS = 0;
    private static final int MSG_LOAD_FAILED = 1;

    private static final int MSG_REFRESH_SUCCESS = 2;
    private static final int MSG_REFRESH_FAILED = 3;


    private static final int MSG_DELETE_SUCCESS = 6;
    private static final int MSG_DELETE_FAILED = 7;
    private static final int MSG_LOAD_NOTNET = 8;

    private static final int SEND_SUCC = 10;
    private static final int SEND_FAIL = 11;
    private int pageNum;
    private int pageSize;
    private NetRequest netRequest;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_theordersell, container, false);
        pageNum = 1;
        pageSize =15;
        list = new ArrayList<>();
        findViews();
        setListeners();
        lv.onLoad();
        EventBus.getDefault().register(this);
        return v;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void findViews() {
        netRequest = new NetRequest(this, getActivity());
//		lin_loadfail = (LinearLayout) v.findViewById(R.id.loadfail);
        img_fail_nonet = (ImageView) v.findViewById(R.id.loadfail_nonet);
        img_fail_notext = (ImageView) v.findViewById(R.id.loadfail_notext);
        tv_fail = (TextView) v.findViewById(R.id.loadfail_tv);
        lv = (AutoListView) v.findViewById(R.id.lv_goods);
        lv.setDivider(null);
        mAdapter = new OrderSellAdapter(list, getActivity(),this);
        lv.setAdapter(mAdapter);

    }

    private void setListeners() {
        lv.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                pageNum=1;
                netRequest.requestSellOrderQuery(2, pageNum + "", pageSize + "","");//便利店订单
            }
        });

        lv.setOnLoadListener(new OnLoadListener() {

            @Override
            public void onLoad() {
                netRequest.requestSellOrderQuery(1, pageNum + "", pageSize + "","");//便利店订单
            }
        });

    }

    @Override
    public void onAfinalFail() {
        if(getActivity()!=null){
            ToastUtils.showTextToast(getActivity(), "请检查本地网络！");
        }
        if(lv!=null){
            lv.onRefreshComplete();
        }
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("zyl", "fragment result:" + result);
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                Log.v("zyl", "data2:" + data.toString());
                String doc_urls = data.getString("doc_url");
                Map<String, String> map = Utils.getMapForJson(doc_urls);
                List<OrderSellBean> orderSellBeans = new ArrayList<>();//最终的item
                JSONArray listArr = data.getJSONArray("list");
                String payed_num  = data.getString("payed_num");
                EventBus.getDefault().post(new CouponUpdateBean(99,payed_num));
                Log.v("zyl","payed_num:"+payed_num);
                for (int i = 0; i < listArr.length(); i++) {
                    OrderSellBean orderSellBean = new OrderSellBean();
                    orderSellBean.setType("1");
                    JSONObject jsonObject = listArr.getJSONObject(i);
                    orderSellBean.setOrder_no(jsonObject.getString("order_no"));//订单号
                    orderSellBean.setOrder_status(jsonObject.getString("status"));//订单状态
                    orderSellBean.setContact_person(jsonObject.getString("contact_person"));//买家名称
                    orderSellBean.setContact_tel(jsonObject.getString("contact_tel"));//买家电话
                    orderSellBean.setDelivery_address(jsonObject.optString("delivery_address"));//地址
                    orderSellBean.setOrder_date(jsonObject.getString("order_date"));//订单时间
                    orderSellBean.setAllCount(jsonObject.getString("item_num"));//总数量
                    orderSellBean.setAllPrice(jsonObject.getString("total_fee"));//总价格
                    orderSellBean.setOrder_id(jsonObject.getString("order_id"));//订单id
                    orderSellBean.setRemark(jsonObject.getString("remark"));//订单留言
                    orderSellBean.setRebate_fee(jsonObject.optString("rebate_fee"));//返利
                    orderSellBean.setLoaded_code(jsonObject.optString("loaded_code"));//提货码
                    List<OrderSellGoodsBean> orderSellGoodsBeanList = new ArrayList<>();
                    JSONArray itemListjsonArray = jsonObject.getJSONArray("itemList");


                    for (int k = 0; k < itemListjsonArray.length(); k++) {
                        JSONObject jsonObjectItem = itemListjsonArray.getJSONObject(k);
                        OrderSellGoodsBean orderSellGoodsBean = new OrderSellGoodsBean();
                        orderSellGoodsBean.setGoodsName(jsonObjectItem.getString("item_name"));//商品名称
                        orderSellGoodsBean.setGoodsCount(jsonObjectItem.getString("item_qty"));//商品数量
                        orderSellGoodsBean.setGoodsPrice(jsonObjectItem.getString("item_total_fee"));//商品应付价格
                        orderSellGoodsBean.setItem_image_info(jsonObjectItem.getString("item_image_info"));//图片id
                        orderSellGoodsBean.setSpecification(jsonObjectItem.getString("item_specification"));//规格
                        orderSellGoodsBean.setType("1");
                        String picUrl = map.get(jsonObjectItem.getString("item_image_info"));
                        if (picUrl == null) {
                            picUrl = "";
                        }
                        orderSellGoodsBean.setPic_url(picUrl);//取出对应图片url
                        orderSellGoodsBeanList.add(orderSellGoodsBean);
                    }
                    Log.v("zyl", "orderSellGoodsBeanList.size:" + orderSellGoodsBeanList.size());
                    orderSellBean.setOrderSellGoodsBeanList(orderSellGoodsBeanList);
                    orderSellBeans.add(orderSellBean);
                }
                int arg1 = data.getJSONObject("page").getInt("page_no");
                lv.onLoadComplete();
                if (arg1== pageNum) {
                    lv.setResultSize(orderSellBeans.size());
                    list.addAll(orderSellBeans);
                    mAdapter.notifyDataSetChanged();
                    pageNum += 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(requestId ==2){
            try {
                JSONObject data = new JSONObject(result);
                Log.v("zyl", "data2:" + data.toString());
                String doc_urls = data.getString("doc_url");
                Map<String, String> map = Utils.getMapForJson(doc_urls);
                List<OrderSellBean> orderSellBeans = new ArrayList<>();//最终的item
                JSONArray listArr = data.getJSONArray("list");
                String payed_num  = data.getString("payed_num");
                EventBus.getDefault().post(new CouponUpdateBean(99,payed_num));
                Log.v("zyl", "payed_num:" + payed_num);
                for (int i = 0; i < listArr.length(); i++) {
                    OrderSellBean orderSellBean = new OrderSellBean();
                    orderSellBean.setType("1");
                    JSONObject jsonObject = listArr.getJSONObject(i);
                    orderSellBean.setOrder_no(jsonObject.getString("order_no"));//订单号
                    orderSellBean.setOrder_status(jsonObject.getString("status"));//订单状态
                    orderSellBean.setContact_person(jsonObject.getString("contact_person"));//买家名称
                    orderSellBean.setContact_tel(jsonObject.getString("contact_tel"));//买家电话
                    orderSellBean.setDelivery_address(jsonObject.optString("delivery_address"));//地址
                    orderSellBean.setOrder_date(jsonObject.getString("order_date"));//订单时间
                    orderSellBean.setAllCount(jsonObject.getString("item_num"));//总数量
                    orderSellBean.setAllPrice(jsonObject.getString("total_fee"));//总价格
                    orderSellBean.setOrder_id(jsonObject.getString("order_id"));//订单id
                    orderSellBean.setRemark(jsonObject.getString("remark"));//订单留言
                    orderSellBean.setRebate_fee(jsonObject.optString("rebate_fee"));//返利
                    orderSellBean.setLoaded_code(jsonObject.optString("loaded_code"));//提货码
                    List<OrderSellGoodsBean> orderSellGoodsBeanList = new ArrayList<>();
                    JSONArray itemListjsonArray = jsonObject.getJSONArray("itemList");

                    for (int k = 0; k < itemListjsonArray.length(); k++) {
                        JSONObject jsonObjectItem = itemListjsonArray.getJSONObject(k);
                        OrderSellGoodsBean orderSellGoodsBean = new OrderSellGoodsBean();
                        orderSellGoodsBean.setGoodsName(jsonObjectItem.getString("item_name"));//商品名称
                        orderSellGoodsBean.setGoodsCount(jsonObjectItem.getString("item_qty"));//商品数量
                        orderSellGoodsBean.setGoodsPrice(jsonObjectItem.getString("item_total_fee"));//商品应付价格
                        orderSellGoodsBean.setItem_image_info(jsonObjectItem.getString("item_image_info"));//图片id
                        orderSellGoodsBean.setSpecification(jsonObjectItem.getString("item_specification"));//规格
                        orderSellGoodsBean.setType("1");
                        String picUrl = map.get(jsonObjectItem.getString("item_image_info"));
                        if (picUrl == null) {
                            picUrl = "";
                        }
                        orderSellGoodsBean.setPic_url(picUrl);//取出对应图片url
                        orderSellGoodsBeanList.add(orderSellGoodsBean);
                    }
                    Log.v("zyl", "orderSellGoodsBeanList.size:" + orderSellGoodsBeanList.size());
                    orderSellBean.setOrderSellGoodsBeanList(orderSellGoodsBeanList);
                    orderSellBeans.add(orderSellBean);
                }
                lv.onRefreshComplete();
                lv.setResultSize(orderSellBeans.size());
                list.clear();
                list.addAll(orderSellBeans);
                mAdapter.notifyDataSetChanged();
                pageNum += 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if(getActivity()!=null){
            Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
        }

    }

    public void onEvent(final OrderAdapterBean event) {

    }
    @Override
    public void refreshUI() {
        Log.v("zyl", "fragment 收到修改UI");
        list.clear();
        mAdapter.notifyDataSetChanged();
        pageNum=1;
        netRequest.requestSellOrderQuery(2, pageNum + "", pageSize + "","");//便利店订单
    }
}